/*
 * $Id: SyncAction.java 67 2002-11-03 18:37:46Z bpruessmann $
 * 
 * Copyright (c) 2001 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.perforce.ui.sync;

import net.sourceforge.perforce.core.internal.P4TeamProvider;
import net.sourceforge.perforce.ui.PerforceUIPlugin;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ui.sync.ITeamNode;
import org.eclipse.team.internal.ui.sync.SyncSet;

/**
  * @version 	$Revision%
  * @author		<a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class SyncAction extends CatchupReleaseAction
{
	public SyncAction(PerforceSyncCompareInput model, ISelectionProvider sp, String label, Shell shell) 
	{
		super(model, sp, label, shell);
	}
	
	protected boolean isEnabled(ITeamNode node) 
	{
		// The update action is enabled only for non-conflicting incoming changes
		return new SyncSet(new StructuredSelection(node)).hasIncomingChanges();
	}
	
	protected void removeNonApplicableNodes(SyncSet set, int syncMode) {
		set.removeConflictingNodes();
		set.removeOutgoingNodes();
	}

	/**
	 * @see CatchupReleaseAction#run(SyncSet, IProgressMonitor)
	 */
	protected SyncSet run(SyncSet syncSet, IProgressMonitor monitor)
	{
		ITeamNode[] changed = syncSet.getChangedNodes();
		if (changed.length == 0) {
			return syncSet;
		}
		
		try
		{
			monitor.beginTask(null, changed.length);
						
			IResource[] resources = getIResourcesFrom(changed);
			P4TeamProvider provider = 
				(P4TeamProvider)RepositoryProvider.getProvider(resources[0].getProject());
			provider.get(resources, IResource.DEPTH_ZERO, monitor);
		}
		catch (TeamException e)
		{
			PerforceUIPlugin.getPlugin().log(e.getStatus());
		}
		finally
		{
			monitor.done();
		}
		
		return syncSet;
	}
}
